package com.hqyj.service.impl;

import com.hqyj.dao.UserDao;
import com.hqyj.pojo.User;
import com.hqyj.pojo.UserAndRole;
import com.hqyj.service.UserService;
import com.hqyj.util.MD5Util;
import com.mysql.cj.callback.UsernameCallback;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YangGuo
 * @version 1.0
 * @date 2021/8/12 11:06
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Override
    public Map<String ,Object> insetUser(User user) {
        final HashMap<String, Object> map = new HashMap<>();
        if(checkUser(user)){
            final String password = MD5Util.md5Hash(user.getPassword(), user.getUsername());
            user.setPassword(password);
            user.setBalance(0.0);
            try {
            userDao.insertUser(user);
            map.put("message","注册成功");
            map.put("count",1);
            }catch (Exception e){
                map.put("message","注册失败");
                map.put("count",0);
            }
        }else {
            map.put("message","注册失败");
            map.put("count",0);
        }
        return map;
    }

    @Override
    public User getOneByPhone(String phone) {
        return userDao.queryByPhone(phone);
    }

    @Override
    public int updateUser(User user) {
        if(user.getUsername()==null){
            return 0;
        }
        return userDao.updateUserByUsername(user);
    }

    @Override
    public User getOnebyEmail(String email) {
        return userDao.queryByEmail(email);
    }

    /**
     * @param username
     * @param roleId
     * @return  Map<String,Object>
     * @author chen3
     * @date 2021-08-16 12:21
     * @description 修改用户角色信息
     */
    @Override
    public  Map<String,Object> modifyRole(String username, Integer roleId) {
        Map<String,Object> result = new HashMap<>();
        int num = userDao.updateRoleByUsername(username, roleId);
        if(num == 1){
            result.put("code",1);
            result.put("message","修改成功！");
            result.put("data",userDao.queryByUsername(username));
        }
        if(num != 1){
            result.put("code",0);
            result.put("message","修改失败！");
            result.put("data",null);
        }
        return result;
    }

    /**
     * @return Map<String, Object>
     * @author chen3
     * @date 2021-08-16 13:03
     * @params 无
     * @description 查询用户列表
     */
    @Override
    public List<UserAndRole> queryAll() {
        return userDao.selectAll();
    }

    @Override
    public boolean checkUser(User user){
        final String address = user.getAddress();
        final String email = user.getEmail();
        final String headerImg = user.getHeaderImg();
        final String name = user.getName();
        final String password = user.getPassword();
        final String phone = user.getPhone();
        final Integer roleId = user.getRoleId();
        final String sex = user.getSex();
        final String username = user.getUsername();
        if(address==null||address.equals("")){return false;}
        if (email==null||!email.contains("@")){return false;}
        if (headerImg==null){
            user.setHeaderImg("default.png");
        }
        if (name==null||name.equals("")){return false;}
        if (password==null||password.equals("")){return false;}
        if (phone==null||phone.equals("")){return false;}
        if (roleId==null){return false;}
        if (sex==null||!(sex.equals("男")||sex.equals("女"))){return false;}
        if (username==null||username.equals("")){return false;}
        return true;
    }
    /**
     * @return User
     * @author chen3
     * @date 2021-08-12 13:24
     * @params username
     * @description 通过用户名查询单个用户对象
     */
    @Override
    public User getOneByUsername(String username) {
        return userDao.queryByUsername(username);
    }

    //使用shiro框架来实现登录
    @Override
    public Map<String, Object> login(String username, String password) {
        Map<String,Object> result = new HashMap<>();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //判断当前是否已经认证过
        if(!subject.isAuthenticated()){
            //未登录认证
            //创建一个令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //登录操作
            try{
                subject.login(token);
            }catch (UnknownAccountException e){
                //未知账号异常
                result.put("code", -1);
                result.put("message",username+"用户不存在");
                return result;
            }catch (IncorrectCredentialsException e){
                //密码错误异常
                result.put("code", -2);
                result.put("message",username+"用户密码错误");
                return result;
            }catch (AuthorizationException e){
                result.put("code",-10);
                result.put("message","认证失败");
                return result;
            }
        }
        //认证通过，获取已保存在shiro session域中的用户信息
        Session session = subject.getSession();
        Object loginUser = session.getAttribute("loginUser");
        result.put("code", 0);
        result.put("message",username +"认证成功");
        //直接返回给控制器方法
        result.put("loginUser",loginUser);
        return result;
    }

    @Override
    public Map<String, Object> logout() {
        //使用shiro框架获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //使用shiro对当前用户登出
        subject.logout();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("message", "成功登出");
        return result;
    }


}
